//
//  CandyTableViewController.m
//  UISearchBar
//
//  Created by lanou3g on 15/9/5.
//  Copyright (c) 2015年 Chason. All rights reserved.
//

#import "CandyTableViewController.h"
#import "Candy.h"

@interface CandyTableViewController ()

@end

@implementation CandyTableViewController
@synthesize candyArray;
@synthesize filteredCandyArray;
@synthesize candySearchBar;

- (void)viewDidLoad {
    [super viewDidLoad];
    candyArray = [NSArray arrayWithObjects:[Candy candyOfCategory:@"A" name:@"a"], [Candy candyOfCategory:@"B" name:@"b"], [Candy candyOfCategory:@"C" name:@"c"], [Candy candyOfCategory:@"D" name:@""], nil];
    
    self.filteredCandyArray = [NSMutableArray arrayWithCapacity:[candyArray count]];
    
    //隐藏范围栏(貌似不需要)
    [candySearchBar setShowsScopeBar:NO];
    [candySearchBar sizeToFit];
    
    CGRect newBounds = self.tableView.bounds;
    newBounds.origin.y = newBounds.origin.y + candySearchBar.bounds.size.height;
    self.tableView.bounds = newBounds;
    NSLog(@"%@", NSStringFromCGRect(candySearchBar.frame));
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.searchDisplayController.searchResultsTableView) {
    return [filteredCandyArray count];} else {
        return [candyArray count];
  }
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil ) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    Candy *candy = nil;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        candy = [filteredCandyArray objectAtIndex:indexPath.row];
    }else{
        candy = [candyArray objectAtIndex:indexPath.row];
    }
    cell.textLabel.text = candy.name;
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    return cell;
}




-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
    // 根据搜索栏的内容和范围更新过滤后的数组。
    // 先将过滤后的数组清空。
    
    [self.filteredCandyArray removeAllObjects];
    // 用NSPredicate来过滤数组。SELF.name指的是数组中每一个Candy对象的“name”属性。”contains[c]“会让predicate搜索“name”属性中的字符串，看看有没有和后面提供的“searchText”一样的字符串。大小写有别。
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name contains[c] %@",searchText];
        NSArray *tempArray = [candyArray filteredArrayUsingPredicate:predicate];
    if (![scope isEqualToString:@"All"]) {
        // 进一步用糖果类别来过滤数据
        NSPredicate *scopePredicate = [NSPredicate predicateWithFormat:@"SELF.category contains[c] %@",scope];
        tempArray = [tempArray filteredArrayUsingPredicate:scopePredicate];
    }     filteredCandyArray = [NSMutableArray arrayWithArray:tempArray];
}



-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
    //当用户改变搜索字符串时，让列表的数据来源重新加载数据
    [self filterContentForSearchText:searchString scope:      [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
    // 返回YES，让table view重新加载。
      return YES;}  -(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {     // 当用户改变搜索范围时，让列表的数据来源重新加载数据
          [self filterContentForSearchText:self.searchDisplayController.searchBar.text scope:      [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
    // 返回YES，让table view重新加载。
          return YES;
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {     // 切入详细视图
    [self performSegueWithIdentifier:@"candyDetail" sender:tableView];}
#pragma mark - Segue 
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"candyDetail"]) {
        UIViewController *candyDetailViewController = [segue destinationViewController];
        //我们需要知道哪个是现在正显示的列表视图，这样才能从相应的数组中提取正确的信息，显示在详细视图中。
if(sender == self.searchDisplayController.searchResultsTableView) {
    NSIndexPath *indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
    NSString *destinationTitle = [[filteredCandyArray objectAtIndex:[indexPath row]] name];
    [candyDetailViewController setTitle:destinationTitle];
} else {
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    NSString *destinationTitle = [[candyArray objectAtIndex:[indexPath row]] name];
    [candyDetailViewController setTitle:destinationTitle];
}
}
}


-(IBAction)goToSearch:(id)sender {     // 如果你担心用户无法发现藏在列表顶端的搜索栏，那我们在导航栏加一个搜索图标。     // 如果你不隐藏搜索栏，那就别加入这个搜索图标，否则就重复了。
    [candySearchBar becomeFirstResponder];
}



@end
